package jwt

import (
	"errors"
	"github.com/dgrijalva/jwt-go"
)

var (
	JwtClient *Jwt
)

//定义jwt 认证的时候发生的错误
var (
	TokenExpired     = errors.New("Token is expired")
	TokenNotValidYet = errors.New("Token not active yet")
	TokenMalformed   = errors.New("That's not even a token")
	TokenInvalid     = errors.New("Couldn't handle this token:")
)

// 定义claims结构
//需要根据场景设计claim格式
type JwtClaims struct {
	UUID       string
	ID         uint
	Username   string
	NickName   string
	RoleId     string
	BufferTime int64

	jwt.StandardClaims
}

//定义JWT结构和对token的操作，包括生成，销毁，合法检查,解析等。
type Jwt struct {
	SigningKey []byte
}

func InitJwt(signingKey string) {
	JwtClient = &Jwt{
		SigningKey: []byte(signingKey),
	}
}

func (j *Jwt) ParseToken(tokenString string) (*JwtClaims, error) {
	token, err := jwt.ParseWithClaims(tokenString, &JwtClaims{}, func(token *jwt.Token) (i interface{}, e error) {
		return j.SigningKey, nil
	})
	if err != nil {
		if ve, ok := err.(*jwt.ValidationError); ok {
			if ve.Errors&jwt.ValidationErrorMalformed != 0 {
				return nil, TokenMalformed
			} else if ve.Errors&jwt.ValidationErrorExpired != 0 {
				// Token is expired
				return nil, TokenExpired
			} else if ve.Errors&jwt.ValidationErrorNotValidYet != 0 {
				return nil, TokenNotValidYet
			} else {
				return nil, TokenInvalid
			}
		}
	}
	if token != nil {
		if claims, ok := token.Claims.(*JwtClaims); ok && token.Valid {
			return claims, nil
		}
		return nil, TokenInvalid

	} else {
		return nil, TokenInvalid

	}

}

func (j *Jwt) CreateToken(claims *JwtClaims) (string, error) {
	token := jwt.NewWithClaims(jwt.SigningMethodHS256, claims)
	return token.SignedString(j.SigningKey)
}
